const express = require('express');
const { dySDK } = require('@open-dy/node-server-sdk');
const app = express();
app.use(express.json());

// 审核通过API
app.post('/api/task/approve', async (req, res) => {
  const { taskId } = req.body;
  try {
    const db = dySDK.database();
    const result = await db.collection('tasks').doc(taskId).update({ status: 'pending' });
    console.log(`[审核通过] taskId: ${taskId}, updated: ${result.updated}`);
    res.json({ success: true, updated: result.updated });
  } catch (e) {
    console.error(`[审核通过失败] taskId: ${taskId}, error: ${e.message}`);
    res.status(500).json({ success: false, message: e.message });
  }
});

// 审核拒绝API
app.post('/api/task/reject', async (req, res) => {
  const { taskId, reason } = req.body;
  try {
    const db = dySDK.database();
    const result = await db.collection('tasks').doc(taskId).update({ status: 'rejected', rejectReason: reason });
    console.log(`[审核拒绝] taskId: ${taskId}, reason: ${reason}, updated: ${result.updated}`);
    res.json({ success: true, updated: result.updated });
  } catch (e) {
    console.error(`[审核拒绝失败] taskId: ${taskId}, error: ${e.message}`);
    res.status(500).json({ success: false, message: e.message });
  }
});

// 下架任务API
app.post('/api/task/offline', async (req, res) => {
  const { taskId } = req.body;
  try {
    const db = dySDK.database();
    const result = await db.collection('tasks').doc(taskId).update({ status: 'off' });
    console.log(`[下架任务] taskId: ${taskId}, updated: ${result.updated}`);
    res.json({ success: true, updated: result.updated });
  } catch (e) {
    console.error(`[下架任务失败] taskId: ${taskId}, error: ${e.message}`);
    res.status(500).json({ success: false, message: e.message });
  }
});

// 健康检查接口
app.get('/api/health', (req, res) => {
  res.send('ok');
});

// 监听端口
const PORT = process.env.PORT || 8000;
app.listen(PORT, () => {
  console.log(`Admin API running on port ${PORT}`);
});